import json

from django import http
from django.conf import settings
from django.contrib.auth import authenticate, login, logout
from django.core.mail import send_mail

from django.shortcuts import render, redirect
from django.views import View
import re

# Create your views here.
from django_redis import get_redis_connection

from carts.utils import merge_cookie_redis_data
from celery_tasks.test.tasks import send_verify_email
from my_taobao.untils.my_encrypt import generate_verify_url, decode_verify_url
from my_taobao.untils.my_loginview import LoginRequiredView
from .models import User, Address


class registerView(View):
    def get(self, request):
        return render(request, 'register.html')

    def post(self, request):
        # 1, 获取参数
        user_name = request.POST.get("user_name")
        pwd = request.POST.get("pwd")
        cpwd = request.POST.get("cpwd")
        phone = request.POST.get("phone")
        msg_code = request.POST.get("msg_code")
        allow = request.POST.get("allow")

        # 2, 校验参数
        # 2,1 为空校验
        if not all([user_name, pwd, cpwd, phone, msg_code, allow]):
            return http.HttpResponse("参数不全")

        # 2,2 两次密码一致
        if pwd != cpwd:
            return http.HttpResponse("两次密码不一致")

        # 2,3 手机号格式正确
        if not re.match(r'^1[3-9]\d{9}$', phone):
            return http.HttpResponse("手机号格式有误")

            # 2,5 短信验证码正确(下一次完成)
            # 2,5 短信验证码正确
            redis_conn = get_redis_connection("code")
            redis_sms_code = redis_conn.get("sms_code_%s" % phone)
            if msg_code != redis_sms_code.decode():
                return http.HttpResponse("短信验证码填写错误")

        # 2,6 协议需要同意
        if allow != 'on':
            return http.HttpResponse("协议需要同意")

        # 3, 数据入库
        # user = User.objects.create(username=user_name, password=pwd, mobile=phone)
        # 可以对密码加密
        user = User.objects.create_user(username=user_name, password=pwd, mobile=phone)

        # 4, 返回响应
        return redirect('/')


class CheckUsernameView(View):
    def get(self, request, username):
        # 1,根据用户名查询用户数量
        count = User.objects.filter(username=username).count()
        # print(count)
        # 2,返回响应
        return http.JsonResponse({'count': count, 'code': 0})


class CheckMobileView(View):
    def get(self, request, mobile):
        # 1,根据用户名查询用户数量
        count = User.objects.filter(mobile=mobile).count()
        # print(count)
        # 2,返回响应
        return http.JsonResponse({'count': count, 'code': 0})


class LoginView(View):
    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        username = request.POST.get('username')
        pwd = request.POST.get('pwd')
        remembered = request.POST.get("remembered")
        to_url=request.GET.get('redirect_to')

        if not all([username, pwd]):
            return http.HttpResponseForbidden('参数不全')

        # 2,2 用户名格式
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.HttpResponseForbidden("用户名格式不对")

        # 2,3 密码格式校验
        if not re.match(r'^[0-9A-Za-z]{8,20}$', pwd):
            return http.HttpResponseForbidden("密码格式不对")
        print(username, pwd)

        user = authenticate(request, username=username, password=pwd)

        if not user:
            return http.HttpResponseForbidden("账号或密码不正确")

        login(request, user)

        if remembered == 'on':
            request.session.set_expiry(3600 * 24 * 2)
        else:
            request.session.set_expiry(0)
        if not to_url:
            to_url='/'
        response = redirect(to_url)
        response.set_cookie('username', user.username, max_age=3600 * 24 * 2)

        #合并购物车
        response=merge_cookie_redis_data(request,response)
        return response


class InfoView(LoginRequiredView):
    def get(self, request):
        context = {
            "username": request.user.username,
            "mobile": request.user.mobile,
            "email": request.user.email,
            "email_active": request.user.email_active,

        }

        return render(request, 'user_center_info.html', context=context)


class EmailView(LoginRequiredView):
    def put(self, request):
        # 1,获取参数
        email = json.loads(request.body.decode()).get('email')

        # 2, 校验参数
        if not email:
            return http.JsonResponse({"code": 500, "errmsg": '参数不全'})
        # #3,数据入库，发送邮件
        verify_url = generate_verify_url(request.user, email)
        send_verify_email.delay(verify_url, email)

        # verify_url=generate_verify_url(request.user,email)
        # result=send_mail(subject='美多商城，验证链接', message=verify_url, recipient_list=[email], from_email=settings.EMAIL_FROM)
        # if  result!=1:
        #     return http.JsonResponse({"code": 500, "errmsg": '发送邮件失败'})
        #3.2数据入库
        request.user.email=email
        request.user.save()

        # 4返回响应
        return http.JsonResponse({"code": 0, "errmsg": '成功！'})


class VerifyView(LoginRequiredView):
    def get(self, request):
        # 1获取token参数
        token = request.GET.get('token')

        # 2解密token
        user = decode_verify_url(token)
        if not user:
            return http.HttpResponse('token失效')

        # 3修改邮箱的激活状态
        user.email_active = True
        user.save()
        return redirect('/info')


# class VerifyEmailView(View):
#     def get(self,request):
#         #1,获取token参数
#         token = request.GET.get('token')
#
#         #2,解密token
#         user = decode_verify_url(token)
#
#         if not user:
#             return http.HttpResponseForbidden("token失效")
#
#         #3,修改邮件的激活状态
#         user.email_active = True
#         user.save()
#
#         #4,返回响应
#         return redirect("/info")


class AddressesView(LoginRequiredView):
    def get(self, request):
        addresses = request.user.addresses.filter(is_deleted=False).all()
        addresses_list = []
        for address in addresses:
            address_dict = {
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email,
                "province_id": address.province_id,
                "city_id": address.city_id,
                "district_id": address.district_id,
            }
            addresses_list.append(address_dict)

        return render(request, 'user_center_site.html', context={'addresses': addresses_list})


class AddressesCreateView(View):
    def post(self, request):
        # 1,获取参数
        data_dict = json.loads(request.body.decode())
        title = data_dict.get("title")
        receiver = data_dict.get("receiver")
        province_id = data_dict.get("province_id")
        city_id = data_dict.get("city_id")
        district_id = data_dict.get("district_id")
        place = data_dict.get("place")
        mobile = data_dict.get("mobile")
        tel = data_dict.get("tel")
        email = data_dict.get("email")

        # 2,校验参数
        if not all([title, receiver, province_id, city_id, district_id, place, mobile, tel, email]):
            return http.JsonResponse({"code": 0, "errmsg": "参数不全"})

        # 3,数据入库
        data_dict["user_id"] = request.user.id
        address = Address.objects.create(**data_dict)

        # 4,返回响应
        data_dict = {
            "code": 0,
            "address": {
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email,
                "province_id": address.province_id,
                "city_id": address.city_id,
                "district_id": address.district_id,
            }
        }
        return http.JsonResponse(data_dict)


# 10, 修改地址
class AddressesUpdateView(View):
    def put(self, request, address_id):
        # 1,获取参数
        data_dict = json.loads(request.body.decode())
        title = data_dict.get("title")
        receiver = data_dict.get("receiver")
        province_id = data_dict.get("province_id")
        city_id = data_dict.get("city_id")
        district_id = data_dict.get("district_id")
        place = data_dict.get("place")
        mobile = data_dict.get("mobile")
        tel = data_dict.get("tel")
        email = data_dict.get("email")

        # 2,校验参数
        if not all([title, receiver, province_id, city_id, district_id, place, mobile, tel, email]):
            return http.JsonResponse({"code": 500, "errmsg": "参数不全"})

        # 3,数据入库,返回的数据是整数,表示修改的行数
        try:
            del data_dict["id"]
            del data_dict["province"]
            del data_dict["city"]
            del data_dict["district"]
            ret = Address.objects.filter(id=address_id).update(**data_dict)
            address = Address.objects.get(id=address_id)
        except Exception as e:
            return http.JsonResponse({"code": 500, "errmsg": "修改失败"})

        # 4,返回响应
        data_dict = {
            "code": 0,
            "address": {
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email,
                "province_id": address.province_id,
                "city_id": address.city_id,
                "district_id": address.district_id,
            }
        }
        return http.JsonResponse(data_dict)

    def delete(self, request, address_id):
        # 1,数据入库
        try:
            ret = Address.objects.filter(id=address_id).update(is_deleted=True)
        except Exception as e:
            return http.JsonResponse({"code": 500, "errmsg": "删除失败"})

        # 2,返回响应
        return http.JsonResponse({"code": 0, "errmsg": "删除成功"})


        # 11, 设置默认


class AddressesDefaultView(LoginRequiredView):
    def put(self, request, address_id):

        # 1,数据入库
        try:
            request.user.default_address_id = address_id
            request.user.save()
        except Exception as e:
            return http.JsonResponse({"code": 500, "errmsg": "设置默认失败"})

        # 2,返回响应
        return http.JsonResponse({"code": 0, "errmsg": "修改城改"})


#12, 标题修改
class AddressesTitleView(View):
    def put(self,request,address_id):
        #1,获取参数
        title = json.loads(request.body.decode()).get("title")

        #2,校验参数
        if not title:
            return http.JsonResponse({"code":500,"errmsg":"参数不全"})

        #3,数据入库
        try:
            Address.objects.filter(id=address_id).update(title=title)
        except Exception as e:
            return http.JsonResponse({"code": 500, "errmsg": "修改失败"})

        #4,返回响应
        return http.JsonResponse({"code": 0, "errmsg": "修改成功"})


class UsersPasswordView(View):
    def get(self,request):
        return render(request,'user_center_pass.html')

    def post(self,request):
        password1=request.POST.get('old_pwd')
        password2=request.POST.get('new_pwd')
        password3=request.POST.get('new_cpwd')

        if not all([password1,password2,password3]):
            return render(request, 'user_center_pass.html')

        if password2!=password3:
            return render(request, 'user_center_pass.html')

        if password1==password2:
            return render(request, 'user_center_pass.html')

        if not request.user.check_password(password1):
            return render(request, 'user_center_pass.html')

        request.user.set_password(password2)
        request.user.save()

        response=redirect('/login')
        logout(request)
        response.delete_cookie("username")
        return response
